<template>
  <!-- 策略列表 -->
  <div class="app-container">
    <el-form class="themm-black themm-bg" :model="queryParams" ref="queryForm" size="small" :inline="true"
      label-width="68px">
      <el-form-item label="标题" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入标题" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="上传时间 " prop="emotional">
        <el-date-picker v-model="dateRange" style="width: 240px" value-format="yyyy-MM-dd" type="daterange"
          range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" class="primary-btn" size="mini"
          @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" class="reset-btn" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="2">
        <el-button type="primary" icon="el-icon-video-play" size="mini" class="primary-btn" @click="handleAdd"
          v-hasPermi="['system:engine:add']">添加</el-button>
      </el-col>
      <el-col :span="22">
        <div class="right-btn">
          <span class="btn-item" :class="tabIndex == item.value ? 'actives' : ''" v-for="(item, index) in tabIndexList"
            @click="handleTabIndex(item.value)">{{item.name}}</span>
        </div>
      </el-col>
    </el-row>
    <el-table v-loading="loading" :data="engineList" class="com-table" stripe>
      <!-- <el-table-column type="selection" width="55" align="center" /> -->
      <el-table-column label="序号" align="center" type="index" />
      <el-table-column label="策略名称" align="center" prop="name" />
      <el-table-column label="选中项" align="center" prop="workStatus">
        <template slot-scope="scope">
          <el-tag 
            class="tag-items"
            style="margin-right: 10px;"
            :style="{backgroundColor: item.bgColor,color: item.color}" 
            v-for="item in setColor(scope.row.elementNames)" 
            :key="item.id">
            {{item.name }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" @click="handleUpdate(scope.row)"
            v-hasPermi="['system:engine:edit']">编辑</el-button>
          <el-button size="mini" type="text" @click="handleDelete(scope.row)"
            v-hasPermi="['system:engine:edit']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination">
      <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
            @pagination="getList" />
    </div>
    

    <!-- 添加或修改采集引擎对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="策略名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="策略" prop="user">
          <el-radio v-model="form.user" :label="userId">个人策略</el-radio>
          <el-radio v-model="form.user" :label="null">公共策略</el-radio>
        </el-form-item>
      </el-form>
      <div class="factor-list">
        <div class="factor-item" v-for="(item, index) in factorsList" :key="index">
          <div class="factor-item-title">{{ item.subType }}</div>
          <div class="sub-factor-list">
            <div class="sub-factor-item" v-for="(subItem, subIndex) in item.data" :key="subIndex">
              <div>{{ subItem.subType }}</div>
              <div class="tag-list">
                <div 
                  class="tag-item" 
                  v-for="(tagItem, tagIndex) in subItem.items" 
                  :key="tagIndex"
                  :class="{ 'active': tagItem.checked }"
                  @click="handleTagClick(tagItem)">{{ tagItem.name }}</div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="resetSelect()" icon="el-icon-refresh-right">重 置</el-button>
        <el-button @click="cancel" class="info-button" icon="el-icon-close">取 消</el-button>
        <el-button type="primary" class="primary-btn" icon="el-icon-circle-plus-outline" @click="submitForm">确 定</el-button>
        
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listStrategy, delStrategy, addStrategy, updateStrategy } from "@/api/library/strategy";
import { listFactors, getFactorsList } from "@/api/library/factors";

export default {
  name: "Engine",
  data() {
    return {
      loading: true,
      total: 0,
      engineList: [],
      factorsList: [],
      title: "",
      open: false,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        workStatus: null,
        name: null,
        startCreateTime:  null,
        endCreateTime: null
      },
      form: {},
      dateRange: [],
      rules: {
        name: [
          { required: true, message: "请输入策略名称", trigger: "blur" },
        ]
      },
      selectList:[],
      tabIndex: 'public',
      tabIndexList:[
        {
          name: '• 个人',
          value: 'private',
        },
        { 
          name: '• 公共',
          value: 'public',
        },
      ],
    };
  },
  computed:{
    userId() {
      return this.$store.getters.userId;
    },
  },
  created() {
    this.getList();
    this.getFactorsList()
  },
  methods: {
    /** 查询采集引擎列表 */
    getList() {
      this.loading = true;
      listStrategy(this.queryParams).then(response => {
        this.engineList = response.rows
        console.log(this.engineList)
        this.total = response.total;
        this.loading = false;
      });
    },
    groupBy(data, keyField = 'type') {
      const treeArray = [];
      data.forEach(item => {
        const subType = item[keyField];
        item.checked = false
        let foundGroup = false;
        for (let i = 0; i < treeArray.length; i++) {
          if (treeArray[i].subType === subType) {
            treeArray[i].items.push(item);
            foundGroup = true;
            break;
          }
        }
        if (!foundGroup) {
          treeArray.push({ subType, items: [item] });
        }
      });
      return treeArray;
    },
    getFactorsList() {
      getFactorsList().then(response => {
        const arr = response.data
        console.log(arr)
        const list = this.groupBy(arr, 'type')
        const data = list.map(key => {
          key.data = this.groupBy(key.items, 'subType')
          return key
        })
        console.log(data)
        this.factorsList = data;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        elements: null,
        allScope: null,
        startCreateTime: null,
        endCreateTime: null,
        user: null
      };
      this.resetForm("form");
    },
    // 切换个人公共
    handleTabIndex(tabIndex){
      console.log(tabIndex)
      this.tabIndex = tabIndex
      if (tabIndex === 'private') {
        this.queryParams.user = this.userId
      } else {
        this.queryParams.user = ''
      }
      this.getList();
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      if(this.dateRange && this.dateRange.length > 0) {
        this.queryParams.startCreateTime = this.dateRange[0];
        this.queryParams.endCreateTime = this.dateRange[1];
      } else {
        this.queryParams.startCreateTime = null;
        this.queryParams.endCreateTime = null;
      }
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "新增策略";
      this.resetSelect()
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      console.log(row)
      const data = JSON.parse(JSON.stringify(row))
      this.selectList = []
      this.selectList = data.elementNames
      console.log(this.factorsList)
      this.factorsList.forEach(item => {
        item.items.forEach(cell =>{
          cell.checked = false
          for (const j in this.selectList) {
            if(this.selectList[j].id == cell.id){
              cell.checked = true
            }
          }
        })
      })
      this.reset();
      this.open = true;
      this.title = "修改策略";
      this.form =  Object.assign({}, row);
    },
    resetSelect(){
      this.selectList = []
      this.factorsList.forEach(item => {
        item.items.forEach(cell =>{
          cell.checked = false
        })
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.form.elements = this.selectList.map(res=> res.id).join(',')
      // this.form.user= this.user==0 ? null : this.user
      if(!this.form.elements){
        return this.$message.error('请选择类型')
      }
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateStrategy(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addStrategy(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除？').then(function () {
        return delStrategy(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    handleTagClick(item){
      console.log(item)
      if(item.checked){
        item.checked = false
        this.selectList.splice(this.selectList.indexOf(item),1)
      }else{
        item.checked = true
        this.selectList.push(item)
      }
      console.log(this.selectList)
    },
    // 按模块区分颜色
    setColor(list){
      return list.map(item => {
        if (item.type === '认知特征') {
          item.color = '#FF7A00'
          item.bgColor = 'rgba(255, 122, 0, 0.08)'
        } else if (item.type === '态度特征') {
          item.color = '#09B844'
          item.bgColor = 'rgba(9, 184, 68, 0.08)'
        } else if (item.type === '情绪特征') {
          item.color = '#0057FF'
          item.bgColor = 'rgba(0, 87, 255, 0.08)'
        } else if (item.type === '文化特征') {
          item.color = '#FF7A00'
          item.bgColor = 'rgba(255, 122, 0, 0.08)'
        } else if (item.type === '性格特征') {
          item.color = '#09B844'
          item.bgColor = 'rgba(9, 184, 68, 0.08)'
        }
        return item
      })
    }
  }
};
</script>
<style lang="scss" scoped>
.factor-list {
  .factor-item {
    border-top: 1px solid #D4DEEA;
    padding: 15px 0;
  }
  .factor-item-title{
    font-size: 16px;
    color: #000;
    font-weight: 700;
    margin-bottom: 15px;
  }
}

.sub-factor-list {

  .sub-factor-item {
    display: flex;
    align-items: center;
    margin-top: 10px;
  }
  
}

.tag-list {
  display: flex;
  margin-left: 15px;

  .tag-item {
    margin-right: 10px;
    border: 1px solid #D4DEEA;
    padding: 4px 15px;
    border-radius: 4px;
    cursor: pointer;
    color: #000;
  }
  .tag-item.active {
    background: #0057FF;
    color: #fff;
  }
}
.right-btn{
    flex: 1;
    text-align: right;
    color: rgba(255, 255, 255, .6);
    padding: 0 20px 20px;
    .btn-item{
      margin-left: 40px;
      cursor: pointer;
    }
    .btn-item.actives{
      color: rgba(0, 87, 255, 1);
      border-bottom: 1px solid rgba(0, 87, 255, 1);
      padding-bottom: 10px;
    }
  }
</style>